package com.example.day16;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;



public class MainActivity extends AppCompatActivity {
    IMyAidlInterface iMyAidlInterface;
    //3.绑定服务回调
    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //绑定服务成功后，返回服务端返回的binder，将其转成IMyAidlInterface调用add方法
            iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);
            int num= 0;//调用服务端的add方法并得到结果
            try {
                num = iMyAidlInterface.add(5,8);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            Toast.makeText(MainActivity.this, ""+num, Toast.LENGTH_SHORT).show();
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            //解除绑定时调用， 清空接口，防止内容溢出
            iMyAidlInterface=null;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent=new Intent();
        intent.setAction("com.guwei");//设置action
        intent.setPackage("com.example.day16");//设置服务端应用进程包名
        bindService(intent,connection, Service.BIND_AUTO_CREATE);

    }
}
